package com.banshuibao.bsb_android.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.ExpertAnswerAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AddressModel;
import com.banshuibao.bsb_android.model.ExpertListModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.ExpertTreeModel;
import com.banshuibao.bsb_android.model.RegionModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshListView;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.PopuWindowsUtil;
import com.banshuibao.bsb_android.util.XToast;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class AreaIdActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2, View.OnClickListener, AdapterView.OnItemClickListener {

    private PullToRefreshListView ptrlv;
    private ListView listView;
    private ExpertAnswerAdapter expertAnswerAdapter;
    private boolean isUp;
    private int startId, endId;
    private int rows;
    private LinearLayout indeustry, category, special, region;
    private TextView indeustry_tv, category_tv, special_tv, region_tv;
    private PopupWindow popupWindow;
    private ExpertTreeModel expertTreeModel;
    private AddressModel addressModel;
    private ImageView background_iv;
    private List<ExpertTreeModel.DataBean.ChildrenBean> tradeList;
    private List<ExpertTreeModel.DataBean.ChildrenBean> taxList;
    private List<ExpertTreeModel.DataBean.ChildrenBean> topicList;
    private List<AddressModel> list;
    private String type = "area";
    private String areaIdUuid = "";
    private String taxId = "";
    private String tag;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String addr;
    private ImageView search_iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_area_id);
        preferences = getSharedPreferences("areaId", MODE_PRIVATE);
        editor = preferences.edit();
        addr = preferences.getString("area_add", "");
        initView();
        getTreeData();
        //判断是否有值，如果有显示当前的，没有使用以下的
        if (!TextUtils.isEmpty(addr)) {
            areaIdUuid = preferences.getString("areaId_uuid", "");
            region_tv.setText(addr);
        } else {
            /**
             * 默认地区第一条
             */
            if (list != null && list.size() > 0) {
                areaIdUuid = list.get(0).getUuid();
                region_tv.setText(list.get(0).getName());
            } else {
                areaIdUuid = "11";
                region_tv.setText("北京");
            }
        }
        getData();
    }

    public void initView() {
        setTitleText("地区特殊规定");
        /**
         * 筛选栏
         */
        category = findViewById(R.id.category);
        category_tv = findViewById(R.id.category_tv);
        region = findViewById(R.id.region);
        region_tv = findViewById(R.id.region_tv);
        category.setOnClickListener(this);
        region.setOnClickListener(this);
        search_iv = findViewById(R.id.search_iv);
        search_iv.setOnClickListener(this);
        /**
         * 列表
         */
        background_iv = findViewById(R.id.backgroud_iv);
        ptrlv = findViewById(R.id.ptrlv);
        ptrlv.setMode(PullToRefreshBase.Mode.BOTH);
        ptrlv.setOnRefreshListener(this);
        listView = ptrlv.getRefreshableView();
        listView.setDivider(null);
        expertAnswerAdapter = new ExpertAnswerAdapter(this, true);
        listView.setAdapter(expertAnswerAdapter);
        listView.setOnItemClickListener(this);
        list = new ArrayList<>();
    }

    /**
     * 设置数据
     */
    public void getData() {
        isUp = false;
        startId = 1;
        endId = startId + 9;
        if (expertAnswerAdapter != null) {
            int count = expertAnswerAdapter.getCount();
            if (count > 10) {
                endId += count - 10;
            }
        }
        requestNet();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        isUp = true;
        endId = startId + 9;
        requestNet();
    }


    public void getTreeData() {
        /**
         * 行业税种专题数据
         */
        HttpUtil.doPost(Constants.Url.EXPERT_TREE, null, new HttpResponse(this, ExpertTreeModel.class) {
            @Override
            public void onResult(Object obj) {
                expertTreeModel = (ExpertTreeModel) obj;
                List<ExpertTreeModel.DataBean> data = expertTreeModel.getData();
                for (int i = 0; i < data.size(); i++) {
//                    if (data.get(i).getName().equals("行业")) {
//                        tradeList = data.get(i).getChildren();
//                    }
                    if (data.get(i).getName().equals("税种")) {
                        taxList = data.get(i).getChildren();
                    }
//                    if (data.get(i).getName().equals("专题")) {
//                        topicList = data.get(i).getChildren();
//                    }
                }
            }
        });

        /**
         * 地区数据
         */
        HttpUtil.doPost(Constants.Url.EXPERT_ADDRESS, null, new HttpResponse(this, RegionModel.class) {
            @Override
            public void onResult(Object obj) {
                RegionModel regionModel = (RegionModel) obj;
                TreeMap<String, String> json = regionModel.getData();
                setAddress(json);
            }
        });
    }

    /**
     * 请求结果
     */
    public void requestNet() {
        showProgressDialog();
        ExpertListModel listModel = new ExpertListModel();
        listModel.setSinceId(startId);
        listModel.setMaxId(endId);
        listModel.setType(type);
        listModel.setUuid(areaIdUuid);
        listModel.setTaxId(taxId);
        HttpUtil.doPost(Constants.Url.EXPERT_ANSWER, listModel, new HttpResponse(this, ExpertResultModel.class) {
            @Override
            public void onResult(Object obj) {
                ExpertResultModel model = (ExpertResultModel) obj;
                rows = model.getRows();
                startId += rows;
                List<ExpertResultModel.DataBean> data = model.getData();
                if (isUp) {
                    expertAnswerAdapter.setUpData(data);
                } else {
                    expertAnswerAdapter.setDownDate(data);
                }
                if (expertAnswerAdapter != null && expertAnswerAdapter.getCount() == 0) {
                    ptrlv.setVisibility(View.GONE);
                    background_iv.setVisibility(View.VISIBLE);
                } else {
                    ptrlv.setVisibility(View.VISIBLE);
                    background_iv.setVisibility(View.GONE);
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                ptrlv.onRefreshComplete();
                cancelProgressDialog();
            }
        });
    }


    /**
     * 默认值
     */
    public void defultData() {
        category_tv.setText("税种");
        category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
        region_tv.setText("地区");
        region_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
    }

    /**
     * 展示弹窗
     */
    public void showDialog(View view, List<ExpertTreeModel.DataBean.ChildrenBean> list, List<AddressModel> addressModelList, final TextView tv, final String type1) {
        PopuWindowsUtil popuWindowsUtil = new PopuWindowsUtil(this);
        if (list != null) {
            popupWindow = popuWindowsUtil.getP(list, null, "tree");
        } else if (addressModelList != null) {
            popupWindow = popuWindowsUtil.getP(null, addressModelList, "address");
        }
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
                region_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down, 0);
            }
        });
        PopuWindowsUtil.showAsDropDown(popupWindow, view, 0, 0);
        popuWindowsUtil.setContent(new PopuWindowsUtil.ItemOnClickListener() {
            @Override
            public void getContent(String name, String uuid) {
                if (!TextUtils.isEmpty(name)) {
                    tag = type1;
                    if (tag.equals("tax")) {
                        if (!"全部".equals(name)) {
                            taxId = uuid;
                            category_tv.setText(name);
                        } else {
                            category_tv.setText("税种");
                            taxId = "";
                        }

                    } else if (tag.equals("area")) {
                        areaIdUuid = uuid;
                        region_tv.setText(name);
                        editor.putString("area_add", name).putString("areaId_uuid", uuid).commit();
                    }
                }
                if (popupWindow != null) popupWindow.dismiss();
                String area = region_tv.getText().toString().trim();
                if (area.equals("地区")) {
                    XToast.showToast(AreaIdActivity.this, "请选择地区");
                    return;
                }
                getData();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null) popupWindow.dismiss();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.category:
                category_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                if (taxList != null && taxList.size() > 0) {
                    showDialog(view, taxList, null, category_tv, "tax");
                } else {
                    exception();
                }

                break;
            case R.id.region:
                region_tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up, 0);
                if (list != null && list.size() > 0) {
                    showDialog(view, null, list, region_tv, "area");
                } else {
                    exception();
                }

                break;
            case R.id.search_iv:
                IntentManager.goSearchVoiceActivity(AreaIdActivity.this);
                break;
        }
    }

    public void setAddress(TreeMap<String, String> hashMap) {
        //遍历集合得到业务id+名称
        for (TreeMap.Entry<String, String> entry : hashMap.entrySet()) {
            list.add(new AddressModel(entry.getValue(), entry.getKey(), ""));
        }
    }

    public void exception() {
        defultData();
        getTreeData();
        XToast.showToast(AreaIdActivity.this, "获取数据失败，请检查网络");
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (expertAnswerAdapter != null && expertAnswerAdapter.getCount() > 0) {
            ExpertResultModel.DataBean dataBean = expertAnswerAdapter.getItem(i - 1);
            //XToast.showToast(ExpertsAnswerActivity.this,"追问价格：+++"+dataBean.getAskPrice()+"元");
            IntentManager.goExpertDetailActivity(AreaIdActivity.this, dataBean.getUuid());
        }
    }
}
